package cn.zlg.common.datadump.service;

import cn.zlg.common.datadump.annotation.DataDumpField;
import com.joysuch.wwyt.core.entity.dsl.QBaseTypeGroupItem;
import com.joysuch.wwyt.core.repository.BaseTypeGroupItemDao;
import com.querydsl.core.Tuple;
import com.querydsl.core.types.Path;
import com.querydsl.core.types.dsl.EntityPathBase;
import com.querydsl.core.types.dsl.SimpleExpression;
import com.querydsl.jpa.impl.JPAQueryFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 使用JPAQueryFactor批量查询单个对象的属性值。保证返回列表和传入的检索列表一一对应，对应位置没有值则存放null
 */
@Service
public class JPABatchQueryPropertyValueService<ENTITY, FROM, TO> {

    @Autowired
    private JPAQueryFactory jpaQueryFactory;

    public List<TO> query(EntityPathBase<ENTITY> entity, SimpleExpression<FROM> keyProperty, Path<TO> valueProperty, List<FROM> values) {
        if(values == null || values.isEmpty()) {
            return Collections.EMPTY_LIST;
        }
        List<FROM> notNullList = values.stream().filter(v -> v != null).collect(Collectors.toList());
        List<Tuple> tuple = jpaQueryFactory.select(keyProperty, valueProperty).from(entity).where(keyProperty.in(notNullList)).fetch();
        List<TO> list = new ArrayList<>(values.size());
        for (int i = 0; i < values.size(); i++) {
            TO name = searchValue(tuple, keyProperty, valueProperty, values.get(i));
            list.add(name);
        }
        return list;
    }


    private TO searchValue(List<Tuple> tuple,SimpleExpression<FROM> keyProperty, Path<TO> valueProperty, FROM id) {
        for (Tuple t : tuple) {
            if (Objects.equals(t.get(keyProperty), id)) {
                return t.get(valueProperty);
            }
        }
        return null;
    }
}
